package com.metal.meta.util;

import com.metal.meta.exception.ResponseCode;
import com.metal.meta.exception.ResponseVo;
import org.springframework.util.ObjectUtils;

/**
 * @author wangye
 * @date 2017年8月7日
 */
public class ResponseUtil {

    /**
     * 依据code构造返回结构
     *
     * @param code
     * @param <T>
     * @return
     */
    public static <T> ResponseVo<T> buildVoByResponseCode(ResponseCode code) {
        return buildVoByResponseCode(code, null);
    }

    /**
     * 依据code和data构造返回结构
     *
     * @param code
     * @param data
     * @param <T>
     * @return
     */
    public static <T> ResponseVo<T> buildVoByResponseCode(ResponseCode code, T data) {
        return buildVo(code.isSuccess(), code.getCode(), code.getMsg(), data);
    }

    /**
     * 自定义参数返回结构
     *
     * @param result
     * @param code
     * @param msg
     * @param data
     * @param <T>
     * @return
     */
    public static <T> ResponseVo<T> buildVo(boolean result, Integer code, String msg, T data) {
        ResponseVo<T> vo = new ResponseVo<>();
        vo.setSuccess(result);
        vo.setCode(code);
        vo.setMsg(msg);
        vo.setData(data);
        return vo;
    }

    /**
     * 判断调用服务是否成功
     *
     * @param responseVo
     * @return
     */
    public static <T> boolean isSuccess(ResponseVo<T> responseVo) {
        if (responseVo == null) {
            return false;
        }
        return responseVo.getCode().intValue() == ResponseCode.CODE_SUCCESS.getCode().intValue();
    }

    /**
     * 判断调用服务返回数据是否为空
     *
     * @param responseVo
     * @return
     */
    public static <T> boolean isDataEmpty(ResponseVo<T> responseVo) {
        if (responseVo == null) {
            return true;
        }
        if (ObjectUtils.isEmpty(responseVo.getData())) {
            return true;
        }
//        if (responseVo.getData() instanceof PageModel) {
//            PageModel page = (PageModel) responseVo.getData();
//            return ObjectUtils.isEmpty(page.getRows());
//        }
        return false;
    }

    /**
     * 服务调用失败或者数据为空
     *
     * @param responseVo
     * @param <T>
     * @return
     */
    public static <T> boolean isFailedData(ResponseVo<T> responseVo) {
        return !isSuccess(responseVo) || isDataEmpty(responseVo);
    }
}
